public without sharing class BudgetProductFillController {

	public String dataJson {get;private set;}

	public String saveJson {get; set;}

    public String searchJson {get; set;}

	public String msg {get; private set;}

	public String companyBoxs {get ;private set;}

    public Boolean isErr {get; private set;}

	public  Boolean isSuccess {get;private set;}

	public Boolean isCanEdit {get; private set;}

	// public Boolean isShowCataLog {get; private set;}

	public String selectId {get; set;}

	public String title {get; private set;}

    public Boolean isOversea {get; private set;}//是否为海外

    public Boolean isImport {get; private set;}//是否为导入数据

    public Boolean canInit {get; private set;} //能否初始计算


    public Boolean isInitCalc {get;private set;}
    public  SalesBudgetTable__c st {get; private set;}

    private Set<String> psets ;

	public BudgetProductFillController() {
           	
        selectId = System.currentPageReference().getParameters().get('id');
        isImport = System.currentPageReference().getParameters().get('import')  != null ;
        SalesBudgetTable__c st = new SalesBudgetTable__c ();
        psets  = new Set<String>();

    }  

    public void init() {

        try {


            User u = [select Profile.Name from User where Id =:UserInfo.getUserId()];
            if(isImport && u.Profile.Name != '系统管理员')throw new DmlException('没有权限!');
            if(isImport )return;

            canInit  = u.Profile.Name == '系统管理员';

            // isShowCataLog = selectId == null; 
            Map<String,String>companyMap = ImportObject.getPicklistValues('SalesBudgetTableDetail__c', 'Company__c', true);
            companyBoxs  = JSON.serialize(companyMap);

            //if(isShowCataLog)dataJson = EncodingUtil.urlEncode(JSON.serialize(getMainTable()), 'UTF-8');
            
            st = [select Id,Year__c,ProductLine__c,CompanyName__c,Province__c,Status__c,OwnerId,LastModifiedDate,CreatedDate,
            BreakdownRatio1__c,BreakdownRatio2__c,BreakdownRatio3__c,BreakdownRatio4__c ,GroupObjectives__c from SalesBudgetTable__c where Id =:selectId];
            
            title = Integer.valueOf( st.Year__c) + '年-' +companyMap.get(st.CompanyName__c) +'-'+ st.Province__c +'-'+ st.ProductLine__c + '-产品预算填制表'; 
            
            isInitCalc =  (st.LastModifiedDate.gettime() - st.CreatedDate.gettime()) < 20000*60  ; 

            isOversea = st.Province__c == '海外';

            System.debug('BudgetProductFillController==>'+ st.Status__c);
        
            isCanEdit = ( st.Status__c == '审批中' || st.Status__c == '审批成功') ? false : true ;
            //筛选字段
            Map<String,List<DataUtil.FieldBean>> tmp  = getSearchObject();
            for (DataUtil.FieldBean dfb  :tmp.get('Product__c') ) {
                if(dfb.name == 'BudgetaryProducts__c'){
                    
                    dfb.type = 'picklist';
                    dfb.data = getCates();
                }
            }

            dataJson = EncodingUtil.urlEncode(JSON.serialize(tmp), 'UTF-8');
            
        }
        catch (Exception e) {
            isErr = true; 
             ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR ,e.getMessage()));


        }
        
        


    }

    public void getDetails(){

    	  Map<String,List<BudgetBean>> tmp = new Map<String,List<BudgetBean>>();
        Set<String> types= new Set<String>{'三方','经销商','医院'};

    	for(SalesBudgetTableDetail__c sd : [select Id ,ProductName__c ,NCCode__c,AccountType__c,Company__c,ProductName__r.SerialNo__c,ProductName__r.Category1__c,
    		Year__c,Province__c,ProductName__r.Spec__c,ProductName__r.Unit__c,ProductName__r.ProductName__c,QuarterlyQuantityNextYearTotal__c,ProductName__r.sealflag__c, 
    		AveragePriceThisYear__c,QuarterlyQuantityThisYear1__c,QuarterlyQuantityThisYear2__c,QuarterlyQuantityThisYear3__c,AveragePriceNextYear__c,
    		QuarterlyQuantityThisYear4__c,NoTaxRevenue1__c,NoTaxRevenue2__c,NoTaxRevenue3__c,NoTaxRevenue4__c,IsAdd__c,ProductName__r.BudgetaryProducts__c,
    		BudgetNoTaxRevenue1__c,BudgetNoTaxRevenue2__c,BudgetNoTaxRevenue3__c,BudgetNoTaxRevenue4__c,BudgetNoTaxRevenueTotal__c,
    		QuarterlyQuantityNextYear1__c,QuarterlyQuantityNextYear2__c,QuarterlyQuantityNextYear3__c,QuarterlyQuantityNextYear4__c 
    		from SalesBudgetTableDetail__c where SalesBudgetTable__c =:selectId ]){
    		    
                if(!sd.IsAdd__c ) psets.add(sd.ProductName__c);
                List<BudgetBean> t = tmp.containsKey(sd.ProductName__c) ? tmp.get(sd.ProductName__c) : new List<BudgetBean>();
                t.add(new BudgetBean(sd));
                tmp.put(sd.ProductName__c, t);


    	}

        //查询封存: 当前产品线自产品牌: NC集团封存 迈克生物SF价格被封存 增加没有的产品
        //and Product__r.Brand__c in: MaccuraBrandUtil.maccura and 
        if(!isOversea){

            String c = '%'+st.ProductLine__c +'%';
            for(Price__c p : [select Id ,Product__c,ClosePrice__c ,
                Product__r.SerialNo__c , Product__r.Brand__c ,Product__r.Spec__c,Product__r.Category0__c,Product__r.NCCode__c ,Product__r.sealflag__c,
                Product__r.BudgetaryProducts__c,Product__r.Unit__c,Product__r.Category1__c ,Product__r.SealCompany__c,Product__r.ProductName__c 
             from Price__c where   Company__c = '迈克生物股份有限公司' and Product__r.NCCode__c like '11%' 
               and Product__r.BudgetaryProducts__c like :c  
               and Product__r.BudgetaryProducts__c like '%迈克%' and Product__r.BudgetaryProducts__c like '%试剂%'  ]){

                Boolean eFlag = tmp.containsKey(p.Product__c );
                if(eFlag && p.ClosePrice__c == true ){

                    for ( BudgetBean b : tmp.get(p.Product__c ) ) {
                        b.seal = true ;
                    }
                
                    continue;
                }


                if(!eFlag && p.ClosePrice__c != true ){

                    List<BudgetBean> t = new List<BudgetBean>();
                    for (String type  : types) {
                        BudgetBean b = new BudgetBean(p.Product__r,st );
                        b.accounttype = type;
                        t.add(b);
                    }
                     psets.add(p.Product__c);

                    tmp.put(p.Product__c , t);

                }
                
            }

        }
        
        List<BudgetBean> t = new List<BudgetBean>();
        for(String k: tmp.keySet()){
            t.addAll(tmp.get(k));
        }
    	dataJson = EncodingUtil.urlEncode(JSON.serialize(t), 'UTF-8');
    }


    /*public List<MainBean>  getMainTable(){

    	List<MainBean> tmp = new List<MainBean>();
    	for (SalesBudgetTable__c st  : [select Id,Company__c,Province__c,Year__c,ProductLine__c  
    		from SalesBudgetTable__c where OwnerId =: UserInfo.getUserId() Order By Company__c,Province__c, ProductLine__c]) {
    		tmp.add(new MainBean(st,false));
    	}
    	return tmp;
    }
    */
    private List<Map<String,String>> getCates(){

        List<Map<String,String>> datasMap = new List<Map<String,String>>();
        for (String s : Label.BudgetProductCates.split(',')) {
            Map<String,String> d = new Map<String,String>();
            d.put('id'  , s);
            d.put('text'  , s);
            datasMap.add(d);
        }

        // for(AggregateResult arg : [select  BudgetaryProducts__c from Product__c 
        //     where  BudgetaryProducts__c != null group by BudgetaryProducts__c ]){
        //     Map<String,String> d = new Map<String,String>();
        //     d.put('id'  , String.valueOf(arg.get('BudgetaryProducts__c')));
        //     d.put('text'  , String.valueOf(arg.get('BudgetaryProducts__c')));
        //     datasMap.add(d);
        // }

        return datasMap;
    }

    


    public void getUndetails(){
        System.debug('getUndetails');
        String year = (System.now().year()+1)+'';
       List<Object> tmp= new List<Object>();
       for(SalesBudgetTable__c s  : [select Id,Year__c,ProductLine__c,CompanyName__c,Province__c,Status__c ,(select Id from SalesBudgetTablejbyu__r ) from SalesBudgetTable__c 
        where Year__c =:year  and RecordType.DeveloperName = 'BudgetBreakdown' ]){

            if(s.SalesBudgetTablejbyu__r != null && s.SalesBudgetTablejbyu__r.size() == 0){
                Map<String,String> m = new Map<String,String>();
                m.put('Id',s.Id);
                m.put('Year__c',s.Year__c);
                m.put('ProductLine__c',s.ProductLine__c);
                m.put('CompanyName__c',s.CompanyName__c);
                m.put('Province__c',s.Province__c);
                tmp.add(m);
            }

       }
       dataJson = EncodingUtil.urlEncode(JSON.serialize(tmp), 'UTF-8');

    }
    @RemoteAction
    public static String  importData(String data,String mainId ){
        String msg = '0';
        try {

            List<Object> products = (List<Object>) JSON.deserializeUntyped(EncodingUtil.urlDecode(data, 'UTF-8'));
            Map<String,List<SalesBudgetTableDetail__c>> details = new  Map<String,List<SalesBudgetTableDetail__c>>();
            for (Object o  : products ) {
                Map<String,Object>mo = (Map<String,Object>)o;
                SalesBudgetTableDetail__c s = new SalesBudgetTableDetail__c();

                s.NCCode__c = DataUtil.getStringValue(mo.get('INVCODE'));
                s.AccountType__c = DataUtil.getStringValue(mo.get('ACCOUNTTYPE'));

                s.NoTaxRevenue1__c = DataUtil.getDecimalValue(mo.get('Q1_NMNY'));
                s.NoTaxRevenue2__c = DataUtil.getDecimalValue(mo.get('Q2_NMNY'));
                s.NoTaxRevenue3__c = DataUtil.getDecimalValue(mo.get('Q3_NMNY'));
                s.NoTaxRevenue4__c = DataUtil.getDecimalValue(mo.get('Q4_NMNY'));

                s.NoTaxRevenueTotal__c = DataUtil.getDecimalValue(mo.get('TOTALMNY')); 

                s.QuarterlyQuantityThisYear1__c  = DataUtil.getDecimalValue(mo.get('Q1_NNUMBER'));
                s.QuarterlyQuantityThisYear2__c  = DataUtil.getDecimalValue(mo.get('Q2_NNUMBER'));
                s.QuarterlyQuantityThisYear3__c  = DataUtil.getDecimalValue(mo.get('Q3_NNUMBER'));
                s.QuarterlyQuantityThisYear4__c  = DataUtil.getDecimalValue(mo.get('Q4_NNUMBER'));
                s.SalesBudgetTable__c = mainId;
                List<SalesBudgetTableDetail__c> t = details.containsKey(s.NCCode__c) ? details.get(s.NCCode__c) :  new List<SalesBudgetTableDetail__c>();
                t.add(s);
                details.put(s.NCCode__c, t);

            }

            //匹配产品
            Map<String,Id>productMap = new Map<String,Id>();
            for (Product__c p :[select Id,NCcode__c from Product__c where NCcode__c in:details.keySet()] ) {
                productMap.put(p.NCCode__c, p.Id);
            }
            List<SalesBudgetTableDetail__c> tmp = new List<SalesBudgetTableDetail__c>();
            for(String nccode : details.keySet()){

                for (SalesBudgetTableDetail__c s  :details.get(nccode) ) {
                    s.ProductName__c = productMap.get(nccode);
                      tmp.add(s);
                }

            }
            SavePoint sp = Database.setSavepoint();
            try {

                if(!tmp.isEmpty())insert tmp;
                
            }catch (Exception e) {
                Database.rollback(sp);
                throw e ;
            }
            
        }catch (Exception e) {
            
            msg = e.getMessage();
        }
        
        return msg;
        



    }

    private Map<String,List<DataUtil.FieldBean>> getSearchObject(){
        Map<String,List<DataUtil.FieldBean>> searchMap = new Map<String,List<DataUtil.FieldBean>>();
        
        Set<String> fieldset = new Set<String>{'ProductName__c','Brand__c','Spec__c','SerialNo__c','NCCode__c'};
        
        if(st.ProductLine__c == null ) fieldset.add('Category1__c');
        Map<String,DataUtil.FieldBean>proMap = DataUtil.getFieldsInfo(Product__c.SObjecttype,fieldset  );
        searchMap.put('Product__c', proMap.values());
        return searchMap;
    }
    public void getProduct(){


        Map<String,Object> searchMap = (Map<String,Object>) JSON.deserializeUntyped(EncodingUtil.urlDecode(searchJson,'UTF-8'));
        String sql = ' select Id  ,ProductName__c ,SerialNo__c , Brand__c ,Spec__c,Category0__c,NCCode__c ,sealflag__c,BudgetaryProducts__c,Unit__c,Category1__c ,SealCompany__c from Product__c where  ';
        sql += '  sealflag__c  !=\'Y\'  ';//and Notice__c != null 
        sql += ' and Id not in (\'' + String.join(new List<String>(psets), '\',\'' )  + '\' ) ';
        if(st.ProductLine__c != null ) sql += ' and BudgetaryProducts__c like \'%'+st.ProductLine__c+'%\'';
        //Brand__c like \'%迈克%\'
       // if(isOversea) sql += ' and Overseasproducts__c  = true ';
       // if(!isOversea) sql += ' and Overseasproducts__c  != true ';
       sql += ' and BudgetaryProducts__c like \'%迈克%\' and BudgetaryProducts__c like \'%试剂%\' '; 

        //sql += ' and Category0__c !=\'仪器\' ';

        if(String.isBlank(DataUtil.getStringValue(searchMap.get('ProductName__c'))) == false) sql += ' and ProductName__c like \'%'+DataUtil.getStringValue(searchMap.get('ProductName__c'))+'%\' ';

        if(String.isBlank(DataUtil.getStringValue(searchMap.get('Brand__c'))) == false) sql += ' and Brand__c like \'%'+DataUtil.getStringValue(searchMap.get('Brand__c'))+'%\' ';

        if(String.isBlank(DataUtil.getStringValue(searchMap.get('Spec__c'))) == false) sql += ' and Spec__c like \'%'+DataUtil.getStringValue(searchMap.get('Spec__c'))+'%\' ';

        if(String.isBlank(DataUtil.getStringValue(searchMap.get('SerialNo__c'))) == false) sql += ' and SerialNo__c like \'%'+DataUtil.getStringValue(searchMap.get('SerialNo__c'))+'%\' ';
 
        // if(String.isBlank(DataUtil.getStringValue(searchMap.get('BudgetaryProducts__c'))) == false) sql += ' and BudgetaryProducts__c like \'%'+DataUtil.getStringValue(searchMap.get('BudgetaryProducts__c'))+'%\' ';
        if(String.isBlank(DataUtil.getStringValue(searchMap.get('Category1__c'))) == false) sql += ' and Category1__c like \'%'+DataUtil.getStringValue(searchMap.get('Category1__c'))+'%\' ';
        if(String.isBlank(DataUtil.getStringValue(searchMap.get('NCCode__c'))) == false) sql += ' and NCCode__c like \'%'+DataUtil.getStringValue(searchMap.get('NCCode__c'))+'%\' ';

        sql += ' limit 200 ';


        List<BudgetBean> tmp = new List<BudgetBean>();
        for (Product__c p  :Database.query(sql)) {
            tmp.add(new BudgetBean(p,st));
        }

        dataJson = EncodingUtil.urlEncode(JSON.serialize(tmp), 'UTF-8');



    }

    public void save(){
    	msg = '';
    	isSuccess = false;

    	List<Object> saveList = (List<Object>)JSON.deserializeUntyped(EncodingUtil.urlDecode(saveJson, 'UTF-8'));
    	List<SalesBudgetTableDetail__c> bdList =new List<SalesBudgetTableDetail__c>();

        Set<String> subset = new Set<String>();
    	for(Object o :saveList  ) {

    		Map<String,Object> mo = (Map<String,Object>)o;
    		SalesBudgetTableDetail__c sd = new SalesBudgetTableDetail__c();
    		sd.Id = DataUtil.getStringValue(mo.get('id'));
            if(sd.Id != null )subset.add(sd.Id);
    		sd.BudgetNoTaxRevenue1__c =  DataUtil.getDecimalValue(mo.get('next_0_profit'));
    		sd.BudgetNoTaxRevenue2__c =  DataUtil.getDecimalValue(mo.get('next_1_profit'));
    		sd.BudgetNoTaxRevenue3__c =  DataUtil.getDecimalValue(mo.get('next_2_profit'));
    		sd.BudgetNoTaxRevenue4__c =  DataUtil.getDecimalValue(mo.get('next_3_profit'));

    		sd.QuarterlyQuantityNextYear1__c = DataUtil.getDecimalValue(mo.get('next_0_count'));
    		sd.QuarterlyQuantityNextYear2__c = DataUtil.getDecimalValue(mo.get('next_1_count'));
    		sd.QuarterlyQuantityNextYear3__c = DataUtil.getDecimalValue(mo.get('next_2_count'));
    		sd.QuarterlyQuantityNextYear4__c = DataUtil.getDecimalValue(mo.get('next_3_count'));
            sd.AveragePriceNextYear__c = DataUtil.getDecimalValue(mo.get('next_avg'));
            //sd.BudgetNoTaxRevenueTotal__c = DataUtil.getDecimalValue(mo.get('next_profit'));
            //sd.QuarterlyQuantityNextYearTotal__c = DataUtil.getDecimalValue(mo.get('next_count'));


            sd.QuarterlyQuantityThisYear1__c = DataUtil.getDecimalValue(mo.get('current_0_count'));
            sd.QuarterlyQuantityThisYear2__c = DataUtil.getDecimalValue(mo.get('current_1_count'));
            sd.QuarterlyQuantityThisYear3__c = DataUtil.getDecimalValue(mo.get('current_2_count'));
            sd.QuarterlyQuantityThisYear4__c = DataUtil.getDecimalValue(mo.get('current_3_count'));
            
            sd.NoTaxRevenue1__c  = DataUtil.getDecimalValue(mo.get('current_0_profit'));
            sd.NoTaxRevenue2__c  = DataUtil.getDecimalValue(mo.get('current_1_profit'));
            sd.NoTaxRevenue3__c  = DataUtil.getDecimalValue(mo.get('current_2_profit'));
            sd.NoTaxRevenue4__c  = DataUtil.getDecimalValue(mo.get('current_3_profit'));

            sd.NoTaxRevenueTotal__c = DataUtil.getDecimalValue(mo.get('current_profit'));

            sd.QuarterlyQuantityThisYearTotal__c = DataUtil.getDecimalValue(mo.get('current_count'));
            sd.AveragePriceThisYear__c = DataUtil.getDecimalValue(mo.get('current_avg'));



            if(sd.Id == null ){

                 sd.Year__c = st.Year__c;
                 sd.Company__c = st.CompanyName__c;
                 sd.Province__c = st.Province__c;
                 sd.ProductLine__c = st.ProductLine__c;
                 sd.ProductName__c = DataUtil.getStringValue(mo.get('productId'));
                 sd.NCCode__c  = DataUtil.getStringValue(mo.get('nccode'));
                 sd.IsAdd__c = true;
                 sd.SalesBudgetTable__c = st.Id;
                 sd.AccountType__c = DataUtil.getStringValue(mo.get('accounttype'));
                 System.debug('BudgetProductFillController==>'+ mo);
                 System.debug('BudgetProductFillController==>'+ sd);
            }

    		bdList.add(sd);
    	}


    	SavePoint sp = Database.setSavepoint();
    	try {
            //删除不要的
            delete [select Id from  SalesBudgetTableDetail__c where Id not in:subset and IsAdd__c = true and SalesBudgetTable__c =:st.Id  ];
    	    
            if(bdList.size()  > 0 )upsert  bdList;
    	    msg = '保存成功!';
    	    isSuccess = true;
    	}
    	catch (Exception e) {
    	    Database.rollback(sp);
    	    msg = '保存失败:'+e.getMessage();
    	}


    }

    public void setNil(){
    	dataJson = '[]';
    	saveJson = '[]';
    	msg = '';
    }

   /* public class MainBean{

    	public String id ;
    	public String productLine  ;
    	public String province;
    	public String company ; 
    	public Boolean isSelected ;
    	public MainBean(SalesBudgetTable__c st,Boolean isSe  ){

    		id = st.Id;
    		productLine = st.ProductLine__c;
    		province = st.Province__c;
    		company = st.Company__c;
    		isSelected =isSe; 

    	}

    }*/
    public class BudgetBean{

    	public String id ;//明细id
    	public String name ; //产品名称

        public Boolean isAdd ;

    	public String serialno ; 
    	public String spec;
    	public String type;
    	public String company;
    	public String accounttype;
    	public String unit ;
    	public String year ;
    	public String province;
        public String producttype;

    	public Decimal current_avg ;
    	
    	public Decimal next_avg ;

        public Boolean seal ; //封存标志


    	public Decimal current_0_count;
    	public Decimal current_1_count;
    	public Decimal current_2_count;
    	public Decimal current_3_count;

    	public Decimal current_0_profit;
    	public Decimal current_1_profit;
    	public Decimal current_2_profit;
    	public Decimal current_3_profit;

    	public Decimal next_0_count;
    	public Decimal next_1_count;
    	public Decimal next_2_count;
    	public Decimal next_3_count;

    	public Decimal next_0_profit;
    	public Decimal next_1_profit;
    	public Decimal next_2_profit;
    	public Decimal next_3_profit;

    	public Decimal next_count;
    	public Decimal next_profit;

        public String nccode;
        public String cate0;
        public String cate1;
        public String brand ; 
        public String originAccounttype;
        public String productId;
        public BudgetBean(){}
    	public BudgetBean(SalesBudgetTableDetail__c sd ){
    		id = sd.Id;
            isAdd = sd.IsAdd__c;
            productId = sd.ProductName__c;
    		name = sd.ProductName__r.ProductName__c; 

    		serialno = sd.ProductName__r.SerialNo__c ;
    		spec = sd.ProductName__r.Spec__c;
            cate1 = sd.ProductName__r.Category1__c;
    		type = '';
            nccode = sd.NCCode__c;
    		company = sd.Company__c;
    		accounttype = sd.AccountType__c;
            originAccounttype = sd.AccountType__c;
    		unit = sd.ProductName__r.Unit__c;
            producttype = sd.ProductName__r.BudgetaryProducts__c;
    		year = sd.Year__c;
    		province = sd.Province__c;
            seal = sd.ProductName__r.sealflag__c == 'Y';

    		current_avg = sd.AveragePriceThisYear__c;
    		current_0_count = sd.QuarterlyQuantityThisYear1__c;
    		current_1_count = sd.QuarterlyQuantityThisYear2__c;
    		current_2_count = sd.QuarterlyQuantityThisYear3__c;
    		current_3_count = sd.QuarterlyQuantityThisYear4__c; 

    		current_0_profit = sd.NoTaxRevenue1__c;
    		current_1_profit = sd.NoTaxRevenue2__c;
    		current_2_profit = sd.NoTaxRevenue3__c;
    		current_3_profit = sd.NoTaxRevenue4__c;

    		next_profit = sd.BudgetNoTaxRevenueTotal__c;
    		next_count = sd.QuarterlyQuantityNextYearTotal__c;
            next_avg = sd.AveragePriceNextYear__c;

    		next_0_profit = sd.BudgetNoTaxRevenue1__c;
    		next_1_profit = sd.BudgetNoTaxRevenue2__c;
    		next_2_profit = sd.BudgetNoTaxRevenue3__c;
    		next_3_profit = sd.BudgetNoTaxRevenue4__c;

    		next_0_count = sd.QuarterlyQuantityNextYear1__c;
    		next_1_count = sd.QuarterlyQuantityNextYear2__c;
    		next_2_count = sd.QuarterlyQuantityNextYear3__c;
    		next_3_count = sd.QuarterlyQuantityNextYear4__c;

    	}

        public BudgetBean(Product__c sd, SalesBudgetTable__c st  ){
            //id = sd.Id;
            name = sd.ProductName__c; 
            productId = sd.Id;

            serialno = sd.SerialNo__c ;
            producttype = sd.BudgetaryProducts__c;

            spec = sd.Spec__c;
            company = st.CompanyName__c;
            isAdd = true;
            if(st.Province__c == '海外')accounttype = '经销商';
            nccode = sd.NCCode__c;
            cate1 = sd.Category1__c;
            cate0 = sd.Category0__c;
            brand = sd.Brand__c;
            seal = sd.sealflag__c == 'Y';

            unit = sd.Unit__c;
            year = st.Year__c;
            province = st.Province__c;

            current_avg = 0;
            current_0_count = 0;
            current_1_count =0 ;
            current_2_count = 0;
            current_3_count = 0; 

            current_0_profit = 0;
            current_1_profit = 0;
            current_2_profit = 0;
            current_3_profit =0 ;

            next_profit = 0;
            next_count = 0;

            next_0_profit = 0;
            next_1_profit = 0;
            next_2_profit = 0;
            next_3_profit = 0;

            next_0_count = 0;
            next_1_count = 0;
            next_2_count = 0;
            next_3_count = 0;

        }


    }
}